<template>
  <div>
  <base-modal
    :show.sync="visible"
    :title="$t('event.setting.additional.component.statisticalDialog.title1')"
    width="1000px"
    class="statistical-dialog"
    @closed="onClose"
  >
    <div class="base-modal-content">
      <div class="statistical-search">
        <div class="search-left">
          <el-date-picker
            v-model="timeArrRange"
            type="daterange"
            range-separator="-"
            :start-placeholder="$t('common.base.startDate')"
            :end-placeholder="$t('common.base.endDate')"
            :default-time="['00:00:00', '23:59:59']"
            value-format="timestamp"
          >
          </el-date-picker>
          <el-input v-model="form.searchKey" :placeholder="$t('event.setting.additional.component.statisticalDialog.pla1')"></el-input>
          <el-input v-model="form.userNameStr" :placeholder="$t('event.setting.additional.component.statisticalDialog.pla2')"></el-input>
          <el-button type="primary" @click="jumpPage(1)">{{$t('common.base.search')}}</el-button>
        </div>
        <div class="search-right" v-if="isButtonDisplayed">
          <a v-if="useExportUrl" :href="exportUrl">{{$t('common.base.export')}}</a>
          <a v-else @click="openExport">{{$t('common.base.export')}}</a>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        style="width: 100%"
        class="page-table statistical-table"
        :highlight-current-row="false"
        border
        header-row-class-name="page-table-header"
        stripe
        tooltip-effect="dark"
        v-loading="loading"
      >
        <el-table-column
          v-for="(column, index) in columns"
          :key="`${column.field}_${index}`"
          :prop="column.fieldName"
          :label="column.displayName"
          :show-overflow-tooltip="true"
          :min-width="column.minWidth || '120px'"
        >
          <template slot-scope="scope">
            <!-- start 事件编号 -->
            <template v-if="column.fieldName === 'eventNo'">
              <a @click="openEventView(scope.row.eventId)">{{ scope.row.eventNo }}</a>
            </template>
            <!-- end 事件编号 -->

            <!-- start 客户、联系人、事件状态、事件类型 -->
            <template v-else-if="column.fieldName === 'cusName' || column.fieldName === 'lmName' || column.fieldName === 'state' || column.fieldName === 'templateName'">
              {{ scope.row[column.fieldName] }}
            </template>
            <!-- end 客户、联系人、事件状态、事件类型 -->

            <!-- start 多选 -->
            <template v-else-if="isMulti(column)">
              {{ (scope.row.cardInfo[column.fieldName] || []).join('，') }}
            </template>
            <!-- end 多选 -->

            <!-- start 操作时间 -->
            <template v-else-if="column.fieldName === 'updateTime'">
              {{ scope.row.cardInfo[column.fieldName] | formatDate }}
            </template>
            <!-- end 操作时间 -->

            <template v-else>
              {{ $formatFormField(column, scope.row, 'cardInfo') }}
            </template>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-footer comment-list-table-footer">
        <div class="comment-list-table-footer-info task-flex task-ai">
          <!-- 共<span class="level-padding">{{ totalElements || 0 }}</span>条 -->
          <!-- <div class="task-font14 task-c6 task-ml12">
            每页
            <el-select
              v-model="form.pageSize"
              placeholder="请选择"
              @change="handleSizeChange(form.pageSize)"
              class="table-footer-select"
            >
              <el-option :label="10" :value="10"></el-option>
              <el-option :label="20" :value="20"></el-option>
              <el-option :label="50" :value="50"></el-option>
            </el-select>
            条
          </div> -->
        </div>
        <el-pagination
          v-if="this.tableData"
          class="comment-list-table-footer-pagination"
          background
          :page-sizes="defaultTableData.defaultPageSizes"
          @current-change="jumpPage"
          @size-change="handleSizeChange"
          :page-size="form.pageSize"
          :current-page="form.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="totalElements"
        >
        </el-pagination>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onClose">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="onClose">{{$t('common.base.confirm')}}</el-button>
    </div>
  </base-modal>
  <!-- start 导出s -->
  <base-export-group
      ref="exportRef"
      :alert="exportAlert"

      :columns="exportColumn"
      :build-params="exportParamsBuild"

      :group="true"
      :validate="exportCountCheck"
      method="post"
      action="/excels/card/eventCardExport"
    />
    <!-- end 导出e -->
</div>
</template>

<script>
/* api */
import * as SettingServiceEventApi from '@src/api/SettingServiceEventApi';
/* util */
import fieldUtil from './cardField';
import { formatDate, objectToUrlParams, nearDateBy, dayTimeEnd } from 'pub-bbx-utils';
import { checkButtonDisplayed } from '@src/util/dom';
/* enum */
import EventStateEnum from '@model/enum/EventStateEnum';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { defaultTableData } from '@src/util/table'

import i18n from '@src/locales';
export default {
  name: 'statistical-dialog',
  props:{
    // 导出数据， true 附加组件表单设置使用，false 选择导出列
    useExportUrl: {
      type: Boolean,
      default: true,
    },

  },
  data() {
    return {
      defaultTableData,
      card: {},
      isButtonDisplayed: checkButtonDisplayed(),
      loading: false,
      visible: false,
      totalElements: 0,
      form: {
        cardId: '',
        pageNum: 1,
        pageSize: 10,
        timeRange: '', // 2020/11/11 - 2020/12/10
        searchKey: '',
        userNameStr: '',
      },
      tableData: [],
      cardFieldsData: [],
      timeArrRange: [],
      CardFieldList:[],
    };
  },
  filters: {
    formatDate(val) {
      if (!val) return '';
      return formatDate(val, 'YYYY-MM-DD HH:mm');
    },
  },
  computed: {
    /* 表头  */
    columns() {
      return fieldUtil.packCustomFields(this.cardFieldsData);
    },
    exportUrl(){
      const { form, card } = this
      const { searchKey, userNameStr } = form
      const params = {
        cardId: card.id,
        searchKey,
        userNameStr,
        ...this.disposeSubmitTime()
      }
      return `/setting/event/card/count/export?${objectToUrlParams(params)}`
    },
    exportColumn(){
      const eventInfo = {
        label: i18n.t('event.eventOrderList.text10'),
        value: 'event',
        columns: [],
      }

      const cardInfo = {
        label: i18n.t('task.AdditionalInformation'),
        value: 'card',
        columns: [],
      }

      for(let item of this.CardFieldList){
        item.export = true;
        item.label = item.displayName;
        item.field = item.fieldName;
        item.value = item.fieldName;

        if(item.tableName === 'event'){
          eventInfo.columns.push(item);
        }else if(item.tableName === 'card'){
          cardInfo.columns.push(item);
        }

      }
      let column = [eventInfo, cardInfo].filter(item => {
        return item.columns && item.columns.length > 0;
      });
      return column
    }
  },
  methods: {
    // 选择导出 Start
    openExport(){
      this.$refs.exportRef.open();
    },
    exportParamsBuild(checkedMap, ids){
      const {card, event} = checkedMap

      const { form } = this
      const { searchKey, userNameStr } = form
      const params = {
        cardId: this.card.id,
        searchKey,
        userNameStr,
        ...this.disposeSubmitTime()
      }

      return {
        eventFields: event.join(','),
        cardFields: card.join(','),
        cardId: this.card.id,
        searchModel: JSON.stringify(params)
      }
    },
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },
    exportCountCheck(ids, max){
      return null
    },
    GetExportColumn() {
      SettingServiceEventApi.getEventCardFieldList({
        cardId: this.card.id
      })
        .then(res => {
          if (res.succ) {
            this.CardFieldList = res?.data || [];
            // 事件列表导出附加组件时获取自定义字段
            if (!this.useExportUrl) this.cardFieldsData = (res?.data || []).filter(f => f.formType);
          }
        })
    },
    // 选择导出 End
    disposeSubmitTime(){
      const [ startTime, endTime ] = this.timeArrRange || []
      // TODO 国际化时间改造 时间参数确认
      return {
        startTime, 
        endTime,
      }
    },
    /* 默认时间 */
    timeRange() {
      this.timeArrRange = [+nearDateBy(1, 'month'), +dayTimeEnd()];
    },
    /* 查看事件详情 */
    openEventView(id) {
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `event_view_${id}`,
      //   title: '事件详情',
      //   close: true,
      //   url: `/event/view/${id}`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventView,
        key: id,
        fromId
      })
    },
    /* 字段是否是多选类型 */
    isMulti(field) {
      let { formType, setting = {} } = field;
      if (formType === 'selectMulti') return true;
      if (formType === 'select' && setting.isMulti) return true;
      return false;
    },
    /* 打开弹窗 */
    openDialog(card = {}) {
      this.card = card;
      this.timeRange();

      if (this.card.id) {
        this.form.cardId = this.card.id;
        this.cardFieldsData = this.card.fields || [];
        this.initCardCountData();
        this.GetExportColumn();
      }

      this.visible = true;
    },
    /* 关闭 */
    onClose() {
      this.visible = false;

      // 初始化form值
      let { form } = this.$options.data();
      this.form = form;
    },
    /**
     * @description 页大小改变操作
     * @param {Number} pageSize 页大小
     */
    handleSizeChange(pageSize) {
      this.form.pageSize = pageSize;
      this.jumpPage(1);
    },
    /**
     * @description 页码跳转
     * @param {Number} pageNum 页码
     */
    jumpPage(pageNum) {
      this.form.pageNum = pageNum;
      this.initCardCountData();
    },
    /* 获取统计列表 */
    initCardCountData() {
      this.loading = true;
      const params = {
        ...this.form,
        ...this.disposeSubmitTime(),
      }
      SettingServiceEventApi.getCardCount(params)
        .then(res => {
          const { total, list = [] } = res;

          let result = [];

          // 处理数据格式
          list.forEach(item => {
            let { eventCardInfo = {}, state, lmName, lmPhone } = item;
            item.cardInfo = eventCardInfo.attribute || {};
            item.state = EventStateEnum.getName(state);
            item.lmName = lmPhone ? `${lmName}/${lmPhone}` : lmName;

            // TODO: 暂时处理多次附加组件数据，后期后端接口优化可删除
            if (this.card.inputType === 'multiple') {
              if (Array.isArray(item.cardInfo)) {
                let attributes = item.cardInfo.map(attr => {
                  return {
                    ...item,
                    cardInfo: attr
                  }
                })

                result.push(...attributes);
              }
            } else {
              result.push(item);
            }
          });

          this.tableData = result;
          this.totalElements = total;
        })
        .finally(() => {
          this.loading = false;
        })
        .catch(err => console.error(err))
    },
  },
};
</script>

<style lang="scss">
.statistical-dialog {
  .base-modal-body {
    padding: 20px;

    .base-modal-content {
      .statistical-search {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .search-left {
          display: flex;
          justify-content: flex-start;
          .el-date-editor {
            margin-right: 12px;
            width: 256px !important;
          }
          .el-input {
            margin-right: 12px;
            width: 168px;
          }
        }

        .search-right {
          a {
            width: 58px;
            height: 32px;
           background: $color-primary-light-1;
            border: 1px solid $color-primary-light-2;
            border-radius: $button-radius-base;
            color: $color-primary;
            text-decoration: none;
            padding: 6px 10px;
            cursor: pointer;
          }
        }
      }

      .statistical-table {
        padding: 0;
        margin: 16px 0;
        border-bottom: 1px solid #ebeef5;

        a {
          width: 100%;
          color: $color-primary;
          cursor: pointer;
          display: block;
          @include text-ellipsis();
        }
      }
    }
  }
}
</style>
